package com.hongkuncheng.cms.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import com.hongkuncheng.cms.exception.FailException;
import com.hongkuncheng.cms.helper.AdminHelper;
import com.hongkuncheng.cms.model.*;
import org.hibernate.FactorySession;
import org.hibernate.Hibernate;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Value;

public class BaseController {

    @Resource
    protected HttpServletRequest request;
    @Resource
    protected HttpServletResponse response;
    @Resource
    protected FactorySession factorySession;
    @Value("${server.port}")
    protected String serverPort;
    @Value("${spring.application.name}")
    protected String applicationName;
    @Value(("${spring.application.directory}"))
    protected String applicationDirectory;
    @Value("${spring.application.isMaster}")
    protected String applicationIsMaster;

    // 系统分页大小
    public int getDataSize() {
        return getDataSize(34);
    }

    // 系统分页大小
    public int getDataSize(int rowheight) {
        int windowHeight = Integer.parseInt(request.getSession().getAttribute("windowheight").toString());
        return (windowHeight - 215 - 52) / rowheight;
    }

    // 向页面打印文字
    public void print(Object msg) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter printer = null;
        try {
            printer = this.response.getWriter();
            printer.print(msg);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            printer.flush();
            printer.close();
        }
    }

    // 向页面打印文字并换行
    public void println(Object msg) {
        print(msg + "\n");
    }

    // 返回成功
    public String view() {
        return view(true);
    }

    // 返回成功
    public String view(boolean compress) {
        if (request.getAttribute("viewcontentpath") == null) {
            String viewContentPath = "pages" + request.getRequestURI();
            if (viewContentPath.endsWith("/")) viewContentPath += "index";
            request.setAttribute("viewcontentpath", viewContentPath + ".html");
        }
        return compress ? "compress" : "normal";
    }

    // 验证权限
    public void checkAdminPermission(String permission) {
        Admin admin = factorySession.load(Admin.class, ((Admin) request.getSession().getAttribute("admin")).getId());
        System.out.println("admin.getAdminReAdminRoles().size():"+admin.getAdminReAdminRoles().size());
        if (!AdminHelper.checkAdminPermission(admin, permission)) {
            throw new FailException("权限认证未通过，请求被拒绝");
        }
    }

    // 写入操作日志
    public void recordLog(String operation) {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        System.out.println("操作日志：" + admin.getAccount() + " " + operation);
        Systemlog systemlog = new Systemlog();
        systemlog.setAccount(admin.getAccount());
        systemlog.setName(admin.getName());
        systemlog.setOperation(operation);
        systemlog.setOperationtime(new Date());
        factorySession.save(systemlog);
    }

    protected Webinfo webinfo;

    // 前台公共方法，返回模板名
    protected void frontpageCommon() {
        // 网站信息
        webinfo = factorySession.get(Webinfo.class, 1);
        request.setAttribute("web", webinfo);
        // 一级菜单
        List<Columns> columns1es = factorySession.createCriteria(Columns.class)
                .add(Restrictions.lt("columnsType.id", 6))
                .add(Restrictions.eq("display", true))
                .add(Restrictions.eq("parentId", 0))
                .addOrder(Order.asc("sort")).list();
        // 二级菜单
        Map<String, List<Columns>> columns2Maps = new HashMap<String, List<Columns>>();
        for (Columns columns1 : columns1es) {
            List<Columns> columns2Temps = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("parentId", columns1.getId()))
                    .add(Restrictions.eq("display", true))
                    .addOrder(Order.asc("sort")).list();
            if (columns2Temps.size() > 0) columns2Maps.put(String.valueOf(columns1.getId()), columns2Temps);
        }
        request.setAttribute("columns1es", columns1es);
        request.setAttribute("columns2Maps", columns2Maps);
        // 部门集合
        List<Department> departments = factorySession.createCriteria(Department.class)
                .add(Restrictions.isNotNull("urldirectory"))
                .addOrder(Order.asc("sort")).list();
        request.setAttribute("departments", departments);
        // 专题活动
        List<Zhuanti> zhuantis = factorySession.createCriteria(Zhuanti.class)
                .addOrder(Order.asc("sort")).setMaxResults(100).list();
        request.setAttribute("zhuantis", zhuantis);
        // 漂浮窗口
        List<Flutter> flutters = factorySession.createCriteria(Flutter.class).list();
        request.setAttribute("flutters", flutters);
        // 网上投票
        Vote vote = factorySession.get(Vote.class, 1);
        request.setAttribute("vote", vote);
        List<VoteOption> voteoptions = factorySession.createCriteria(VoteOption.class).list();
        request.setAttribute("voteoptions", voteoptions);
        // 友情链接
        List<Friendlink> friendlinks = factorySession.createCriteria(Friendlink.class)
                .addOrder(Order.asc("sort")).list();
        request.setAttribute("friendlinks", friendlinks);
        // 表单
        List<Form> forms = factorySession.createCriteria(Form.class)
                .addOrder(Order.asc("sort")).list();
        request.setAttribute("forms", forms);
    }

}
